﻿using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;
using RuoVea.ExIdGen;
using System.Collections.Generic;
using System.Net;
using System.Security.Claims;
using System.Web;

namespace OAuthServer.Controllers;

public class LoginController : Controller
{
    [HttpGet]
    public IActionResult Index(string returnUrl)
    {
        returnUrl = returnUrl ?? Url.Content("~/");
        ViewBag.ReturnUrl = HttpUtility.UrlEncode(returnUrl);
        return View();
    }


    [HttpPost]
    public async Task<IActionResult> Index(string returnUrl, string type)
    {
        returnUrl = returnUrl ?? Url.Content("~/"); // 默认返回主页
        //cookie
        await HttpContext.SignInAsync("cookie", new ClaimsPrincipal(
                new ClaimsIdentity(
                        new Claim[]
                        {
                            new Claim("sub",IdGenerator.Id+"",ClaimValueTypes.Integer64 ),
                            new Claim(ClaimTypes.Name,"admin"),
                            new Claim(ClaimTypes.NameIdentifier,Guid.NewGuid().ToString())
                        }, "cookie"
                    )
                )
            );

        // 如果有returnUrl并且是绝对URL，则重定向回该地址
        if (Url.IsLocalUrl(returnUrl))
        {
            // todo 判断参数 合法就跳转 ，不合法就转首页
            return Redirect(returnUrl);
        }
        else
        {
            return this.RedirectToAction(nameof(HomeController.Index), "Home");
        } 
    }

    [HttpGet("/sign-out")]
    public async Task<IActionResult> Logout(string returnUrl)
    {
        returnUrl = returnUrl ?? Url.Content("~/");
        await HttpContext.SignOutAsync("cookie");
        if (Url.IsLocalUrl(returnUrl)) {
            var response = Response;
            ThreadPool.QueueUserWorkItem(async state =>
            {
                  Redirect("https://host.docker.internal:5001/sign-out");
            });
            return  Redirect(returnUrl);
        }
        else { 
            return Redirect(returnUrl);
        }
    }
}
